<?php

namespace Modules\Chat\Base;

use App\Helper\ErrorHelper;
use App\Helper\LogHelper;
use App\Helper\RSAHelper;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as RoutingController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class BaseController extends RoutingController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    use CommonPoolMethod;

    public function __construct()
    {
        if(function_exists('inWechat') && inWechat())
        {
            $wechat = app('wechat.official_account');
            $js = $wechat->jssdk;
            $wxConfig = $js->buildConfig(
                ['onMenuShareAppMessage', 'onMenuShareTimeline', 'showMenuItems', 'hideAllNonBaseMenuItem',
                 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'hideOptionMenu'
                ],
                false);
            LogHelper::info("wxConfig::::". $wxConfig);
            view()->share('wxConfig', $wxConfig);
            view()->share('isInWeixin', '1');
            view()->share('canShare', '0');
        }
        else
        {
            view()->share('isInWeixin', '0');
        }
    }

    protected function returnData($code,$message,$data=[])
    {
        return response()->json(
            [
                "error_code"    => $code,
                "error_message" => $message,
                "data"          => $data,
            ], 200);
    }

    //从sesson中取出当前用户
    public function getCurrentWxUser()
    {
        // 1.检测用户是否在app登录，有登录即返回
        $mobile = session('appmobile');
        if ($mobile)
        {
            $user = User::where('mobile',$mobile)->first();

            return $user;
        }

        // 2.以下为微信登录用户返回
        $wxUser   = session('wechat.oauth_user.default');
        LogHelper::info('wxUser_data_type', gettype($wxUser));

        $user = User::where('wx_open_id',  $wxUser['id'])->first();

        if (empty($user))
        {
            LogHelper::info('wxUser_data', $wxUser);
            $user = new User;
            $user->wx_union_id = $wxUser->original['unionid'] ? $wxUser->original['unionid'] : '';
            $user->wx_open_id  = $wxUser['id'];
            $user->wx_userinfo = json_encode($wxUser->original);
            $user->nickname    = $wxUser->nickname;
            $user->avatar      = $wxUser->avatar;
            $user->gender      = $wxUser->original['sex'] ? $wxUser->original['sex']: 0;
            $user->save();

            $user = $this->service("Im\RongCloud")->setUserToken($user);
        }

        return $user;
    }

    /**
     * @return bool
     * 判断是否是微信浏览器
     */
    function isWeixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        } else {
            return false;
        }
    }

    public function getCurrentUserWxApp()
    {
        $wxUser   = session('wechat.oauth_user.default');
        $wxAppUser = UserWxapp::where('wx_open_id',  $wxUser['id'])->first();

        return $wxAppUser;
    }

    public function getCurrentUser()
    {
        // 1.检测用户是否在app登录，有登录即返回
        $mobile = session('appmobile');
        if ($mobile)
        {
            $user = User::where('mobile',$mobile)->first();

            return $user;
        }

        // 2.以下为微信登录用户返回
        $wxUser   = session('wechat.oauth_user.default');

//        $wxAppUser = UserWxapp::where('wx_open_id',  $wxUser['id'])->first();
        $user = User::where('id',  1)->first();

        return $user;
    }


    /**
     * 验证request参数，如果缺少，则返回错误
     * @param Request $request
     * @param array $checkParams
     * @return \Illuminate\Http\JsonResponse|null
     */
    public function checkParams(Request $request, $checkParams = [])
    {
        $lackParams = $this->filterEmptyParams($request, $checkParams);
        if (count($lackParams) > 0) {
            return $this->returnLackMsg($lackParams);
        }
    }

    /**
     * 验证request中是否存在指定参数
     * @param Request $request
     * @param array $params
     * @return array
     */
    public function filterEmptyParams(Request $request, array $params)
    {
        if (empty($params)) return [];

        $lackParams = [];
        foreach ($params as $param) {

            $paramValue = $request->input($param);

            if (isset($paramValue) && !empty($paramValue)) continue;

            $lackParams[] = $param;
        }
        return $lackParams;
    }

    public function returnLackMsg($params)
    {
        return $this->apiError('缺少参数：'.implode(',', $params));
    }

    public function lackMsgResponse($params)
    {
        return $this->apiError('缺少参数：'.implode(',', $params));
    }

    /**
     * 成功时返回的数据
     *
     * @param array  $data 返回的数据
     * @param string $msg  描述
     * @param string $error_code 状态值
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiSuccess($data, $msg = ErrorHelper::ERROR_OK_MESSAGE, $error_code = ErrorHelper::ERROR_OK)
    {
        if (!is_array($data)){
            $data = (object)$data;
        }

        return response()->json(
            [
                "error_code"    => $error_code,
                "error_message" => $msg,
                "data"          => $data,
            ], 200);
    }

    /**
     * 失败时返回的数据
     *
     * @param string $msg 描述
     * @param array  $data 返回的数据
     * @param string $error_code 状态值
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiError($msg = ErrorHelper::MESSAGE_FAILED, $data = [], $error_code = ErrorHelper::ERROR_FAILED)
    {
        return response()->json(
            [
                "error_code"    => $error_code,
                "error_message" => $msg,
                "data"          => (object)$data,
            ], 200);
    }

    /**
     * 获取http_header中的手机号（医生端才有mobile）
     * @return mixed|string
     */
    public function getMobile()
    {
        //取得原始数据
        $mobile = isset($_SERVER['HTTP_MOBILE']) ? $_SERVER['HTTP_MOBILE'] : '';
        $tflag  = isset($_SERVER['HTTP_TFLAG']) ? $_SERVER['HTTP_TFLAG'] : '';

        LogHelper::info('HTTP_MOBILE', $mobile);
        LogHelper::info('tflag', $tflag);

        if ($tflag != 123)
        {
            $mobile = RSAHelper::decrypt($mobile);
        }
        LogHelper::info('mobile', $mobile);

        return $mobile;
    }

    /**
     * 判断平台类型
     * return IOS 或者 Android 或者 other
     */
    public function getPlatFormType()
    {
        if(strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone')||strpos($_SERVER['HTTP_USER_AGENT'], 'iPad'))
        {
            return 'IOS';
        }
        else if(strpos($_SERVER['HTTP_USER_AGENT'], 'Android'))
        {
            return 'Android';
        }
        else
        {
            return 'other';
        }
    }

    /**
     * 获取用户的注册状态
     * @param $user_id
     * @return bool
     */
    public function getUserRegisterStatus($user_id)
    {
        $user = User::find($user_id);

        if(!$user || empty($user->mobile))
        {
            return false;
        }
        return true;
    }

}
